﻿using AutoMapper;
using EquipmentModule.Contracts;
using EquipmentModule.Entity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;

namespace EquipmentModule.Controllers
{
    /// <summary>
    /// 流向仪
    /// </summary>
    [ApiController]
    [Route("Equipment/[controller]")]
    public class FlowChartController : ControllerBase
    {
        private readonly ILogger _logger;
        private readonly IWebHostEnvironment _env;
        private readonly IEquipmentHistoryService _service;
        private readonly IMapper _mapper;
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="env"></param>
        /// <param name="service"></param>
        public FlowChartController(IMapper mapper, ILogger<FlowChartController> logger, IWebHostEnvironment env, IEquipmentHistoryService service)
        {
            _logger = logger;
            _env = env;
            _service = service;
            _mapper = mapper;
        }
        /// <summary>
        /// 接收push过来的数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Add(FlowChart flowChart)
        {
            _logger.LogInformation(flowChart.ToString());
            if (flowChart.DataType == "04" || flowChart.DataType=="05")
            {
                DateTime dt = DateTime.Now;
                string db = Common.GetHeader4DB(this.Request);
                //验证该设备是否存在
                bool exist = _service.Exist(flowChart.DeviceId);
                if (!exist)
                {
                    return Ok(new { code = "200", message = "", data = "" });
                }
                //db = "soadb1597154229";
                EquipmentHistoryItem info = new EquipmentHistoryItem();
                info.CreateTime = dt;
                info.DevId = flowChart.DeviceId;
                info.TagName = "电压";
                info.Value = flowChart.BatteryLevel;
                info.Value1 = flowChart.Temperature;
                info.Ticks = (long)(info.CreateTime - new DateTime(1970, 1, 1)).TotalMilliseconds;
                _service.Add(info, db);

                info = new EquipmentHistoryItem();
                info.CreateTime = dt;
                info.DevId = flowChart.DeviceId;
                info.TagName = "流向";
                info.Value = flowChart.Direction;
                info.Value1 = "";
                info.Ticks = (long)(info.CreateTime - new DateTime(1970, 1, 1)).TotalMilliseconds;
                _service.Add(info, db);
            }
            return Ok(new { code = "200", message = "", data = "" });
        }
    }
}
